//
//  IconViewController.m
//  IconMaster
//
//  Created by 为为 on 13-5-27.
//  Copyright (c) 2013年 为为. All rights reserved.
//

#import "IconViewController.h"
#import "CPAnimationSequence.h"
#import "TextViewController.h"
#import "TextNoteLabel.h"
#import "CFontPickerViewController.h"
#import "CImageUtil.h"
#import "CameraAlbumViewController.h"
#import "AlbumPhotoPicker.h"
#import "ToggleSegmentedControl.h"
#import "ImageGridTableViewController.h"
#import "UIActionSheet+Blocks.h"
//#import "UIAlertViewBlock/UIAlertView+Blocks.h"
#import "UIAlertView+Blocks.h"
#import "DBOperation.h"
#import "AdAndHint.h"

#define BUTTON_TABLE_VIEW_HEIGHT	80

#define KEY_ICON			@"icon"
#define KEY_SKIN			@"skin"
#define KEY_FRAME			@"frame"
#define KEY_DECORATE		@"decorate"
#define KEY_PHOTO			@"photo"
#define KEY_TEXT			@"text"


@interface IconViewController ()

@end

@implementation IconViewController

@synthesize iconImage = _iconImage;

- (id)initWithIconView:(CIconView *)aIconView
{
    self = [super init];
    if (self) {
        iconView = aIconView;
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    changed = NO;
    [self initControllerDict];
	[self initNavigationItem];
	[self initIconView];
	[self initButtons];
	[self initSpriteContainerView];
	[self initAdmob];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
	[self setIconViewPlaceholder:nil];
    [super viewDidUnload];
}

#pragma mark navigationItem

- (void)initNavigationItem
{
	
}

#pragma mark button

- (void)initButtons
{
    segmentDictArray = [NSMutableArray array];
    [segmentDictArray addObject:@{@"title": NSLocalizedString(@"icon",@""), @"key": KEY_ICON}];
    [segmentDictArray addObject:@{@"title": NSLocalizedString(@"skin",@""), @"key": KEY_SKIN}];
    [segmentDictArray addObject:@{@"title": NSLocalizedString(@"frame",@""), @"key": KEY_FRAME}];
    [segmentDictArray addObject:@{@"title": NSLocalizedString(@"decor",@""), @"key": KEY_DECORATE}];
    [segmentDictArray addObject:@{@"title": NSLocalizedString(@"photo",@""), @"key": KEY_PHOTO}];
    [segmentDictArray addObject:@{@"title": NSLocalizedString(@"text",@""), @"key": KEY_TEXT}];
   
    NSMutableArray* itemArray = [NSMutableArray array];
    for (NSDictionary* dict in segmentDictArray) {
        [itemArray addObject:[dict objectForKey:@"title"]];
    }
	
	float leftRightMargin = 5;
    segmentContrl = [[UISegmentedControl alloc] initWithItems:itemArray];
    segmentContrl.frame = CGRectMake(leftRightMargin, self.view.bounds.size.height-segmentContrl.frame.size.height-20, self.view.bounds.size.width-2*leftRightMargin, segmentContrl.frame.size.height);
	segmentContrl.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
	segmentContrl.momentary = true;
    [segmentContrl addTarget:self action:@selector(segmentedControlValueChanged:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:segmentContrl];
}

- (void)segmentedControlValueChanged:(UISegmentedControl*)sender
{
    NSString* thisKey = nil;
	NSDictionary* dict = [segmentDictArray objectAtIndex:sender.selectedSegmentIndex];
	thisKey = [dict objectForKey:@"key"];
    changed = YES;
    [self switchButtonToKey:thisKey];
}

- (void)switchButtonToKey:(NSString*)toKey
{
    if ([toKey isEqualToString:KEY_TEXT]) {
        TextViewController* controller = [self ensureTextViewController];
		
        UIControl* backgroundControl = [[UIControl alloc] initWithFrame:self.view.bounds];
        backgroundControl.backgroundColor = [UIColor clearColor];
		backgroundControl.frame = self.view.bounds;
        [backgroundControl addTarget:self action:@selector(textControllerBackgroundTapped:) forControlEvents:UIControlEventTouchDown];
        [self.view addSubview:backgroundControl];
		
        [self.view addSubview:controller.view];
        [controller.view setFrame:CGRectMake(0, self.view.bounds.size.height-controller.view.frame.size.height, self.view.bounds.size.width, controller.view.frame.size.height)];
        [controller textButtonPressed:nil];
    } else {
		[self.spriteContainer unselectAllSprite];
		
		if ([toKey isEqualToString:KEY_PHOTO]) {
			[UIActionSheet showInView:self.view
							withTitle:nil
					cancelButtonTitle:NSLocalizedString(@"Cancel", @"")
			   destructiveButtonTitle:nil
					otherButtonTitles:@[NSLocalizedString(@"Camera", @""), NSLocalizedString(@"Album", @"")]
							 tapBlock:^(UIActionSheet *actionSheet, NSInteger buttonIndex) {
								 if (buttonIndex == 0) {
									 [self cameraButtonPressed];
								 } else if (buttonIndex == 1) {
									 [self albumButtonPressed];
								 }
							 }];
		} else {
			ImageGridTableViewController* controller = nil;
			
			if ([toKey isEqualToString:KEY_ICON]) {
				controller = [[ImageGridTableViewController alloc] initWithArray:[DBOperation iconGroupArray]];
				controller.imagePressedBlock = ^(ImageGridTableViewController* ctl, NSUInteger rowIndex, NSUInteger imageIndex, UIImage* image) {
                    if (rowIndex == 0) {
                        CIconView* aIconView = [DBOperation getIconViewFromSavedIconWithID:[DBOperation getIDFromImage:image]];
                        [self resetIconView:aIconView];
                        [self dismissViewControllerAnimated:YES completion:nil];
                    } else {
                        [iconView setBackgroundImage:image];
                        [self dismissViewControllerAnimated:YES completion:nil];
                    }
				};
				
				controller.imageDeletedBlock = ^(ImageGridTableViewController* ctl, NSUInteger rowIndex, NSUInteger imageIndex, UIImage* image) {
					[DBOperation deleteSavedIconWithID:[DBOperation getIDFromImage:image]];
				};
			} else if ([toKey isEqualToString:KEY_SKIN]) {
				controller = [[ImageGridTableViewController alloc] initWithArray:[DBOperation skinGroupArray]];
				controller.imagePressedBlock = ^(ImageGridTableViewController* ctl, NSUInteger rowIndex, NSUInteger imageIndex,UIImage* image) {
					[iconView setBackgroundImage:image];
                    [self dismissViewControllerAnimated:YES completion:nil];
				};
			} else if ([toKey isEqualToString:KEY_FRAME]) {
				controller = [[ImageGridTableViewController alloc] initWithArray:[DBOperation frameGroupArray]];
				controller.imagePressedBlock = ^(ImageGridTableViewController* ctl, NSUInteger rowIndex, NSUInteger imageIndex,UIImage* image) {
                    int iid = [DBOperation getIDFromImage:image];
                    if (iid != DEFAULT_ICON_ID.integerValue) {
    					[iconView setFrameImage:image];
                    }
                    [self dismissViewControllerAnimated:YES completion:nil];
				};
			} else if ([toKey isEqualToString:KEY_DECORATE]) {
				controller = [[ImageGridTableViewController alloc] initWithArray:[DBOperation decoGroupArray]];
				controller.imagePressedBlock = ^(ImageGridTableViewController* ctl, NSUInteger rowIndex, NSUInteger imageIndex,UIImage* image) {
                    int iid = [DBOperation getIDFromImage:image];
                    if (iid != DEFAULT_ICON_ID.integerValue) {
    					[self addSpriteWithImage:image];
                    }
                    [self dismissViewControllerAnimated:YES completion:nil];
				};
			}
			
			controller.cancelPressedBlock = ^(ImageGridTableViewController* ctl) {
                [self dismissViewControllerAnimated:YES completion:nil];
			};
			[self presentViewController:controller animated:YES completion:^{
                [AdAndHint showInterstitialViewInController:controller withRatioPercent:60];
			}];
		}
	}
}

#pragma mark controller dict

- (void)initControllerDict
{
    controllerDict = [NSMutableDictionary dictionary];
}

- (void)textControllerBackgroundTapped:(id)sender
{
    UIControl* control = (UIControl*)sender;
    [control removeFromSuperview];
	
	TextViewController* controller = [controllerDict objectForKey:KEY_TEXT];
	if (controller) {
		[controller hideKeyboard];
		
		[UIView animateWithDuration:0.4
						 animations:^{
							 CGRect frame = controller.view.frame;
							 frame.origin.y = self.view.bounds.size.height;
							 controller.view.frame = frame;
						 }
						 completion:^(BOOL finished) {
							 [controller.view removeFromSuperview];
						 }
		 ];
        
        if (controller.textNoteSprite) {
            [self removeEmptyTextSprite:controller.textNoteSprite];
        }
	}
}

#pragma mark camera

- (void)cameraButtonPressed
{
	AlbumPhotoPicker* picker = [[AlbumPhotoPicker alloc] init];
	picker.controller = self;
	picker.allowsEditing = true;
	picker.finishBlock = ^(AlbumPhotoPicker* photoPicker, NSDictionary* infoDict) {
		[self setIconImageWithPickerDict:infoDict];
        [self dismissViewControllerAnimated:YES completion:nil];
	};
	[picker pickCamera];
}

- (void)albumButtonPressed
{
	AlbumPhotoPicker* picker = [[AlbumPhotoPicker alloc] init];
	picker.controller = self;
	picker.allowsEditing = true;
	picker.finishBlock = ^(AlbumPhotoPicker* photoPicker, NSDictionary* infoDict) {
		[self setIconImageWithPickerDict:infoDict];
        [self dismissViewControllerAnimated:YES completion:nil];
	};
	[picker pickAlbum];
}

- (void)setIconImageWithPickerDict:(NSDictionary*)dict
{
	UIImage* image = [dict objectForKey:UIImagePickerControllerEditedImage];
	[self setIconImage:image];
}

#pragma mark iconview

- (void)initIconView
{
    [self resetIconView:iconView];
}

- (void)resetIconView:(CIconView *)aIconView
{
    if (iconView) {
        [iconView removeFromSuperview];
    }
    
    __block typeof(self) bself = self;
    
    if (!aIconView) {
        iconView = (CIconView*)GetObjectFromXib([CIconView class], @"CIconView");
        iconView.frame = self.iconViewPlaceholder.frame;
        iconView.layer.cornerRadius = ICON_RADIUS;
        iconView.layer.masksToBounds = true;
        iconView.autoresizingMask = self.iconViewPlaceholder.autoresizingMask;
    } else {
        iconView = aIconView;
    }

	iconView.spriteContainer.spriteSelected = ^(SpriteContainerView* container, SpriteView* sprite) {
		[bself moveSpriteFromIconView:sprite];
	};
	self.iconViewPlaceholder.hidden = true;
	[self.view insertSubview:iconView belowSubview:self.iconViewPlaceholder];
    changed = NO;
}

#pragma mark spriteview

- (void)initSpriteContainerView
{
	__block typeof(self) bself = self;
	[self.view bringSubviewToFront:self.spriteContainer];
	self.spriteContainer.hidden = true;
	self.spriteContainer.spriteSelected = ^(SpriteContainerView* spc, SpriteView* sprite) {
		
	};
	self.spriteContainer.spriteUnselected = ^(SpriteContainerView* spc, SpriteView* sprite) {
		[bself moveSpriteToIconView:sprite];
	};
	self.spriteContainer.spriteDelete = ^(SpriteContainerView* spc, SpriteView* sprite) {
		[bself updateSpriteContainerVisibility];
	};
	self.spriteContainer.shouldUnselectSprite = ^(SpriteContainerView* spc, SpriteView* sprite){
		return [bself shouldUnselectSprite:sprite];
	};
}

- (void)addSpriteWithImage:(UIImage*)image
{
	[iconView addSpriteWithImage:image];
	self.spriteContainer.hidden = false;
}

- (void)addSpriteWithName:(NSString*)imageName
{
	[iconView addSpriteWithName:imageName];
	self.spriteContainer.hidden = false;
}

- (void)moveSpriteToIconView:(SpriteView*)sprite
{
    changed = TRUE;
    
	ChangeViewsSuperView(sprite, iconView.spriteContainer);
    [self removeEmptyTextSprite:sprite];
	self.spriteContainer.hidden = true;
	
	TextNoteLabel* textNote = [self getTextNoteFromSprite:sprite];
	if (textNote) {
		[textNote hideKeyboard];
        
        TextViewController* controller = [controllerDict objectForKey:KEY_TEXT];
		controller.textNoteSprite = nil;
	}
}

- (void)moveSpriteFromIconView:(SpriteView*)sprite
{
	self.spriteContainer.hidden = false;
	ChangeViewsSuperView(sprite, self.spriteContainer);
	
	TextNoteLabel* textNote = [self getTextNoteFromSprite:sprite];
    if (textNote) {
        TextViewController* controller = [self ensureTextViewController];
        controller.textNoteSprite = sprite;
    }
}

- (void)removeEmptyTextSprite:(SpriteView*)sprite {
	TextNoteLabel* textNote = [self getTextNoteFromSprite:sprite];
	if (textNote) {
		if (!textNote.text || [textNote.text isEqualToString:@""]) {
			[sprite removeFromSuperview];
		}
	}
    
    [self updateSpriteContainerVisibility];
}

- (BOOL)shouldUnselectSprite:(SpriteView*)sprite
{
	TextNoteLabel* textNote = [self getTextNoteFromSprite:sprite];
	if (textNote) {
		if ([textNote isKeyboardShown]) {
			[textNote hideKeyboard];
			return false;
		}
	}
	return true;
}

- (void)updateSpriteContainerVisibility
{
	if ([[self.spriteContainer subviews] count]) {
		self.spriteContainer.hidden = false;
	} else {
		self.spriteContainer.hidden = true;
	}
}

- (void)addTextNodeSpriteIfNeed
{
	TextViewController* textController = [controllerDict objectForKey:KEY_TEXT];
	if (!textController.textNoteSprite) {
		TextNoteLabel* textLabel = [[TextNoteLabel alloc] initWithFrame:CGRectMake(0, 0, 114, 114)];
		SpriteView* sprite = [[SpriteView alloc] init];
		[sprite setView:textLabel];
		[iconView addSprite:sprite];
        textController.textNoteSprite = sprite;
	}
}

- (TextNoteLabel*)getTextNoteFromSprite:(SpriteView*)sprite
{
	TextNoteLabel* textLabel = nil;
    textLabel = (TextNoteLabel*)[sprite getViewWithClass:[TextNoteLabel class]];
    
	return textLabel;
}

- (TextViewController*)ensureTextViewController
{
    __block typeof(self) bself = self;
    TextViewController* controller = [controllerDict objectForKey:KEY_TEXT];
    if (!controller) {
        controller = [[TextViewController alloc] init];
        [controllerDict setObject:controller forKey:KEY_TEXT];
        controller.textFieldPressedBlock = ^(TextViewController* tvc) {
            [bself addTextNodeSpriteIfNeed];
        };
    }
    return controller;
}

#pragma mark action

- (IBAction)wrongButtonPressed:(id)sender {
    if (0) {
        [UIAlertView showWithTitle:nil
                           message:NSLocalizedString(@"discard hint", @"")
                 cancelButtonTitle:NSLocalizedString(@"Cancel", @"")
                 otherButtonTitles:@[NSLocalizedString(@"OK", @"")]
                          tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                              if (buttonIndex == [alertView cancelButtonIndex]) {
                                  
                              } else {
                                  changed = false;
                                  if (self.wrongButtonPressedBlock) {
                                      self.wrongButtonPressedBlock(self);
                                  }
                              }
                          }];
    } else {
        if (self.wrongButtonPressedBlock) {
            self.wrongButtonPressedBlock(self);
        }
    }
}

- (IBAction)rightButtonPressed:(id)sender {
	if (self.rightButtonPressedBlock) {
		[self.spriteContainer unselectAllSprite];
		self.rightButtonPressedBlock(self);
	}
    
    if (changed) {
        changed = NO;
		[DBOperation insertSavedIconWithIconView:iconView];
    }
}

- (UIImage *)iconImage
{
	UIImage* image = nil;
	
	image = [CImageUtil imageFromView:iconView];
	
	return image;
}

- (void)setIconImage:(UIImage *)iconImage
{
	if (iconImage) {
//		[buttonTableViewDict setObject:iconImage forKey:@"originalImage"]; 		
	}
	[iconView setBackgroundImage:iconImage];
}

#pragma mark admob

- (void)initAdmob
{
	GADBannerView* bannerView =
	[AdAndHint showBannerViewInController:self view:self.view frame:CGRectZero];
	CGRect bannerFrame = bannerView.frame;
	bannerFrame.origin.x = 0;
	bannerFrame.origin.y = segmentContrl.frame.origin.y-10-bannerFrame.size.height;
	bannerView.frame = bannerFrame;
	bannerView.autoresizingMask = segmentContrl.autoresizingMask; 
}

@end
